import React from 'react';
import ReactECharts from 'echarts-for-react';

interface EchartsAreaProps {
  data: any[];
  xField: string;
  yField: string;
  height?: number;
  smooth?: boolean;
  color?: string;
  areaStyle?: any;
  area?: {
    style?: {
      fill?: string;
    };
  };
  [key: string]: any;
}

const EchartsArea: React.FC<EchartsAreaProps> = ({
  data = [],
  xField,
  yField,
  height = 400,
  smooth = false,
  color = '#1890ff',
  areaStyle,
  area,
  ...rest
}) => {
  // 确保 data 是数组
  const safeData = Array.isArray(data) ? data : [];

  // 处理渐变色
  const getAreaColor = () => {
    if (areaStyle && typeof areaStyle === 'function') {
      const style = areaStyle();
      if (style.fill && style.fill.includes('l(270)')) {
        // 解析线性渐变 l(270) 0:#ffffff 0.5:#7ec2f3 1:#1890ff
        return {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: '#ffffff' },
            { offset: 0.5, color: '#7ec2f3' },
            { offset: 1, color: '#1890ff' },
          ],
        };
      }
      return style.fill || color;
    }

    if (area?.style?.fill) {
      return area.style.fill;
    }

    return color;
  };

  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const param = params[0];
        return `${xField}: ${param.axisValue}<br/>${yField}: ${param.value}`;
      },
    },
    xAxis: {
      type: 'category',
      data: safeData.map(item => item[xField]),
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        data: safeData.map(item => item[yField]),
        type: 'line',
        smooth,
        lineStyle: {
          color,
        },
        itemStyle: {
          color,
        },
        areaStyle: {
          color: getAreaColor(),
        },
        symbol: 'none',
      },
    ],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
  };

  return (
    <ReactECharts
      option={option}
      style={{ height: `${height}px`, width: '100%' }}
      {...rest}
    />
  );
};

export default EchartsArea;
